package ru.ifmo.croak.impl.stress.post.team1;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.croak.api.Message;
import ru.ifmo.croak.api.PostService;
import ru.ifmo.croak.util.CroakFactory;

import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;

public class PostStressMain implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(PostStressMain.class);
    private static final int AUTHORS_NUMBER = 20;
    private static final int AUTHOR_LEN = 10;
    private static final int MESSAGE_LEN = 1000;
    private static final int MESSAGE_NUMBER = 100000;
    public static final double SPACES_PERCENT = 0.15;

    private final Random random = new Random();
    private final PostService postService;

    public PostStressMain(String name) {
        String postProviderName = CroakFactory.getInstance().getProperty(name + ".provider");
        postService = CroakFactory.getInstance().getImplementation(PostService.class, postProviderName);
    }

    private String randomString(int maxLen) {
        int len = random.nextInt(maxLen) + 1;
        char[] s = new char[len];
        for (int i = 0; i < len; i++) {
            if (random.nextDouble() < SPACES_PERCENT) {
                s[i] = ' ';
            } else {
                s[i] = (char) ('a' + random.nextInt('z' - 'a'));
            }
        }
        return new String(s);
    }

    private Message genMessage(String author, int index) {
        Message message = new Message();
        message.setId(UUID.randomUUID());
        message.setTime(System.currentTimeMillis());
        message.setAuthor(author);
        message.setText(randomString(MESSAGE_LEN) + " " + index);
        return message;
    }

    public void run() {
        ArrayList<String> authors = new ArrayList<String>();
        for (int i = 0; i < AUTHORS_NUMBER; i++) {
            authors.add(randomString(AUTHOR_LEN));
        }
        for (int i = 0; i < MESSAGE_NUMBER; i++) {
            postService.postMessage(genMessage(authors.get(random.nextInt(authors.size())), i));
            if (i % 1000 == 0) {
                log.debug("posted {} messages", i);
            }
        }
    }
}
